<script>
import Vue from 'vue';
import { mapState, mapMutations } from 'vuex';
import setGrayFilter from '@/common/setIsGrayFilter.js';
export default {
    mixins: [setGrayFilter],
    computed: {
        ...mapState(['isGrayFilter']),
    },
    // 下方已有methods
    // methods: {
    // 	...mapMutations([
    // 		'setcity',
    // 		'setloaded',
    // 		'ocJoinShow',
    // 		'setIsGrayFilter',
    // 	]),
    // },
    onLaunch: function (options) {
        if (!uni.$u.test.isEmpty(options.query)) {
            let sceneInfo = this.getScene(options.query.scene);
            uni.setStorageSync('referee_id', sceneInfo.uid);
            uni.setStorageSync('token', '');
        }
		if (options) {
		    let sceneInfo = this.getScene(options.query.scene);
			if(sceneInfo.stallid>0){
				console.log('sceneInfo.stallid', sceneInfo.stallid);
				this.$store.commit('stall_setid',sceneInfo.stallid);
			}
		}
        console.log('referee_id', uni.getStorageSync('referee_id'));
        //广告弹窗状态
        uni.setStorageSync('advertisement', true);
        // console.log('App Launch')
        //获取地址
        this.getlocation();
    },
    onShow: function () {
        // console.log('App Show')
        // #ifdef MP-WEIXIN
        const updateManager = uni.getUpdateManager();
        updateManager.onCheckForUpdate(function (res) {
            // 请求完新版本信息的回调
            // console.log(res.hasUpdate);
            if (res.hasUpdate == true) {
                updateManager.onUpdateReady(function (res) {
                    uni.showModal({
                        title: '更新提示',
                        content: '新版本已经准备好，是否重启应用？',
                        success(res) {
                            if (res.confirm) {
                                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                                updateManager.applyUpdate();
                            }
                        },
                    });
                });

                updateManager.onUpdateFailed(function (res) {
                    // 新的版本下载失败
                });
            }
        });
        // #endif
    },
    onHide: function () {
        // console.log('App Hide')
    },
    data() {
        return {
            street: '',
            nearbyLatitude: '',
            nearbyLongitude: '',
            minAddressExit: '',
        };
    },
    globalData: {
        isUniModel: 0,
        storeInfo: {},
        addressInfo: {},
        warehouseInfo: {},
    },
    methods: {
        ...mapMutations([
            'setcity',
            'setloaded',
            'ocJoinShow',
            'setIsGrayFilter',
        ]),
        // 处理小程序码参数
        getScene(scene) {
            let scene_new = decodeURIComponent(scene);
            let info = {};
            var list = scene_new.split('&');
            for (var i = 0; i < list.length; i++) {
                info[list[i].split(':')[0]] = list[i].split(':')[1];
            }
            return info;
        },
        handlePageData(list, data, page) {
            if (data.page_count == page) {
                list = list.concat(data.items);

                if (page == 1) {
                    list = data.items;
                }

                return {
                    list: list,
                    loadmoreStatus: 'nomore',
                };
            } else if (data.page_count > page) {
                let loadmoreStatus = 'loadmore';
                if (page == 1) {
                    list = data.items;
                } else {
                    list = list.concat(data.items);
                }

                return {
                    list: list,
                    loadmoreStatus: loadmoreStatus,
                };
            } else {
                list = data.items;
                return {
                    list: list,
                    loadmoreStatus: 'nomore',
                };
            }
        },
        async getlocation() {
            // 清理缓存再次进入页面不存在token、token过期，需要验证
            await this.checkUser();
            console.log('LET GO+++++++++++++++++++++++++++++');
            let self = this;
            uni.showLoading({
                title: '定位中',
            });
            // h5 获取位置

            // #ifdef H5
            // uniapp h5获取位置信息，并且处理报错信息获取定位权限
            console.log('------------------------------');
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                    this.showPosition,
                    this.showError,
                    { enableHighAccuracy: true, maximumAge: 0 }
                );
            } else {
                alert('暂不支持地理定位功能');
            }
            // #endif
            // #ifdef MP-WEIXIN
            console.log('=====================');
            // 小程序获取位置
            uni.getLocation({
                type: 'gcj02',
                success: (resLocation) => {
                    console.log('当前位置的经度：' + resLocation.longitude);
                    console.log('当前位置的纬度：' + resLocation.latitude);
                    // console.log("res",res);
                    this.nearbyLongitude = resLocation.longitude;
                    this.nearbyLatitude = resLocation.latitude;
                    uni.$u.api.tencentMapLocation(
                            resLocation.latitude,
                            resLocation.longitude
                        )
                        .then((res) => {
                            console.log('address', res);
                            let temp_province =
                                res.data.result.address_component.province;
                            let temp_city =
                                res.data.result.address_component.city;
                            let stree = (res.data && res.data.result && res.data.result.address_component && res.data.result.address_component.street) || '';
                            this.street = (res.data && res.data.result && res.data.result.address_component && res.data.result.address_component.street) || '';
                            console.log(stree, 'stree');
                            // self.$store.commit('setMapAddress',{address_id:0,address:stree});
                            //获取最近地址
                            uni.$u.api
                                .minDistanceAddress({
                                    lng: resLocation.longitude,
                                    lat: resLocation.latitude,
                                })
                                .then((res) => {
                                    console.log(
                                        res,
                                        'mindis',
                                        res.address.distance <= 200
                                    );
                                    if (res.address.distance <= 200) {
                                        self.getCityNode(
                                            temp_province,
                                            temp_city,
                                            res.address.address_id,
                                            res.address.detail,
                                            false
                                        );
                                    } else {
                                        self.getCityNode(
                                            temp_province,
                                            temp_city,
                                            res.address.address_id,
                                            res.address.detail,
                                            true
                                        );
                                    }
                                })
                                .catch((er) => {
                                    // uni.hideLoading()
                                    console.log('er', er);
                                    self.getCityNode(
                                        temp_province,
                                        temp_city,
                                        0,
                                        '',
                                        true
                                    );
                                });
                        })
                        .catch(() => {
                            uni.hideLoading();
                            self.$store.commit('resetcity');
                            self.$store.commit('ocJoinShow', true);
                            self.setCity('广西壮族自治区', '南宁市', 0, {
                                lng: '',
                                lat: '',
                            });
                        });
                },
                fail: (ex) => {
                    console.log('----------------------------');
                    console.log(ex, 'fail location');
                    uni.hideLoading();
                    self.openSetting();
                    // self.$isResolve();
                },
            });
            // #endif
        },
        showPosition(position) {
			let self = this;
            // 成功获取位置后的回调函数
            const latitude = position.coords.latitude;
            const longitude = position.coords.longitude;
            console.log('h5：纬度：' + latitude + '，经度：' + longitude);
			this.nearbyLongitude = longitude;
			this.nearbyLatitude = latitude;
			uni.$u.api.jsonPTencentMapLocation(
					latitude,
					longitude
				)
				.then((res) => {
					console.log('address', res);
					let temp_province =
						res.result.address_component.province;
					let temp_city =
						res.result.address_component.city;
					let stree =
						(res &&
							res.result &&
							res.result.address_component &&
							res.result.address_component.street) ||
						'';
					this.street =
						(res &&
							res.result &&
							res.result.address_component &&
							res.result.address_component.street) ||
						'';
					console.log(stree, 'stree');
					// self.$store.commit('setMapAddress',{address_id:0,address:stree});
					//获取最近地址
					uni.$u.api
						.minDistanceAddress({
							lng: longitude,
							lat: latitude,
						})
						.then((res) => {
							console.log(
								res,
								'mindis',
								res.address.distance <= 200
							);
							if (res.address.distance <= 200) {
								self.getCityNode(
									temp_province,
									temp_city,
									res.address.address_id,
									res.address.detail,
									false
								);
							} else {
								self.getCityNode(
									temp_province,
									temp_city,
									res.address.address_id,
									res.address.detail,
									true
								);
							}
						})
						.catch((er) => {
							// uni.hideLoading()
							console.log('er', er);
							self.getCityNode(
								temp_province,
								temp_city,
								0,
								'',
								true
							);
						});
				})
				.catch((e) => {
					console.log(e, '????????????????????????????');
					uni.hideLoading();
					self.$store.commit('resetcity');
					// self.$store.commit('ocJoinShow', true);
					self.setCity('广西壮族自治区', '南宁市', 0, {
						lng: '',
						lat: '',
					});
				});
        },
        showError(error) {
            // 获取位置失败后的回调函数
            switch (error.code) {
                case error.PERMISSION_DENIED:
                    alert('用户拒绝了请求地理定位');
                    break;
                case error.POSITION_UNAVAILABLE:
                    alert('位置信息不可用');
                    break;
                case error.TIMEOUT:
                    alert('请求用户地理位置超时');
                    break;
                case error.UNKNOWN_ERROR:
                    alert('发生未知错误');
                    break;
            }
            uni.hideLoading();
            this.$store.commit('resetcity');
            this.$store.commit('ocJoinShow', true);
            this.setCity('广西壮族自治区', '南宁市', 0, {
                lng: '',
                lat: '',
            });
        },
        async checkUser() {
            return new Promise(async (resolve, reject) => {
                uni.$u.api
                    .checkUserLoginToken()
                    .then(async (res) => {
                        resolve('ok');
                        // console.log('check login now ------------>>----------->>')
                    })
                    .catch(async (er) => {
                        console.log('er');
                        reject(er);
                    });
            });
        },
        //获取门店
        getCityNode(
            temp_province,
            temp_city,
            temp_mapid,
            temp_mapdetail,
            isMoreDistance
        ) {
            let self = this;
            uni.$u.api
                .getCityStore({
                    province: temp_province,
                    city: temp_city,
                })
                .then(async (res) => {
                    // 页面图标/首页置灰 待改
                    const { page_data = {} } = res;
                    self.setPageTab(page_data, 0);
                    // 城市
                    if (res.getstore == 0) {
                        console.log('AppVue no city store');
                        self.$store.commit('resetcity');
                        self.$store.commit('ocJoinShow', true);
                        self.setCity(temp_province, temp_city, 0, {
                            lng: '',
                            lat: '',
                        });
                    } else {
                        console.log('have city store');
                        // 最近的收货地址address
                        if (!isMoreDistance) {
                            console.log('is no More Distance');
                            self.$store.commit('setMapAddress', {
                                address_id: temp_mapid,
                                address: temp_mapdetail,
                                lng: this.nearbyLongitude,
                                lat: this.nearbyLatitude,
                            });
                            self.setCity(temp_province, temp_city, temp_mapid, {
                                lng: this.nearbyLongitude,
                                lat: this.nearbyLatitude,
                            });
                        } else {
                            // 存储距离最近地址, 0? temp_mapid?
                            await this.getNearbyAddress(this.street, {
                                latitude: this.nearbyLatitude,
                                longitude: this.nearbyLongitude,
                            });
                            self.setCity(temp_province, temp_city, 0, {
                                lng: this.nearbyLongitude,
                                lat: this.nearbyLatitude,
                            });
                        }
                        self.$store.commit('setcity', {
                            province: temp_province,
                            city: temp_city,
                        });
                    }
                })
                .catch((ex) => {
                    console.log(ex);
                    console.log('error AppVue no city store');
                    self.$store.commit('resetcity');
                    self.$store.commit('ocJoinShow', true);
                    self.setCity(temp_province, temp_city, 0, {
                        lng: '',
                        lat: '',
                    });
                });
        },
        // 获取附近地址列表，e:当前位置，{经、纬度}，以及最近收获地址
        async getNearbyAddress(
            e,
            addressLatLgt = { latitude: '', longitude: '' }
        ) {
            let nearbyAddressList = [];
            const { latitude, longitude } = addressLatLgt;
            let boundary = `nearby(${latitude},${longitude},200,1)`;
			// #ifdef H5
			// h5NearBy
			// #endif
            // #ifdef MP-WEIXIN
            const res = await uni.$u.api.tencentMapSearchPlace({
                boundary,
                category: '280000,100000,160000,140000,210000',
            });
            if (res.data.status == 0) {
                nearbyAddressList = nearbyAddressList.concat(res.data.data);
                // nearbyAddressList.sort((a, b) => a._distance - b._distance);
                const nearbyAddress = nearbyAddressList[0];
                const { id, title, location = {} } = nearbyAddress;
                this.$store.commit('setMapAddress', {
                    address_id: 0,
                    address: title,
                    lng: location.lng,
                    lat: location.lat,
                });
                return nearbyAddress;
            } else {
                return { id: 0 };
            }
			// #endif
        },
        //设置商户
        setCity(temp_province, temp_city, temp_mapid, params) {
            const { lng, lat } = params;
            let self = this;
            uni.$u.api
                .getCity({
                    province: temp_province,
                    city: temp_city,
                    usaddrid: temp_mapid,
                    lng,
                    lat,
                })
                .then((res) => {
                    uni.hideLoading();
                    self.$isResolve();
                    console.log('go show');
                    self.$store.commit('setloaded');
                })
                .catch((ex) => {
                    uni.hideLoading();
                    self.$isResolve();
                    console.log('go show');
                    self.$store.commit('setloaded');
                });
        },
        openSetting() {
            const that = this;
            if (uni.getSetting) {
                console.log('11111111111111111111111111');
                uni.getSetting({
                    success: (res) => {
                        if (res.authSetting['scope.userLocation'] == true) {
                            uni.showModal({
                                title: '提示',
                                content: '请检查是否开启定位服务',
                                success: function (res) {
                                    if (res.confirm) {
                                        that.getlocation();
                                    } else if (res.cancel) {
                                        that.showerrormsg();
                                        console.log('用户点击取消');
                                    }
                                },
                            });
                        } else {
                            uni.showModal({
                                title: '定位失败',
                                content:
                                    '开启定位服务，我们将更好的为您匹配城市哦',
                                cancelText: '暂时不开',
                                confirmText: '现在开启',
                                confirmColor: '#BB0024',
                                success: (res) => {
                                    if (res.confirm) {
                                        uni.openSetting({
                                            success: (res) => {
                                                let authSettings =
                                                    res.authSetting;
                                                if (
                                                    authSettings[
                                                        'scope.userLocation'
                                                    ] == true
                                                ) {
                                                    that.getlocation();
                                                } else {
                                                    console.log('用户未开启');
                                                    that.showerrormsg();
                                                }
                                            },
                                        });
                                    } else {
                                        that.showerrormsg();
                                    }
                                },
                            });
                        }
                    },
                });
            } else {
                console.log('2222222222222222222222222222222222');
                this.showerrormsg();
            }
        },
        showerrormsg() {
            const that = this;
            uni.showToast({
                title: '您未开启定位服务，自动为您切换至总站',
                icon: 'none',
            });
            // setTimeout(function(){
            console.log('canel go show');
            that.$isResolve();
            // },3000)
        },
    },
};
</script>

<style lang="scss">
@import 'uview-ui/index.scss';
/*每个页面公共css */

page {
    width: 100%;
    max-width: 100%;
}

.container {
    min-height: 100vh;
    background-color: #f6f6f6;
    color: #333333;
}

.bg-fff {
    background: #ffffff;
}

.flex {
    display: flex;
}

.flex-center {
    display: flex;
    align-items: center;
    justify-content: center;
}

.flex-column-center {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
}

.flex-align-center {
    display: flex;
    align-items: center;
}

.flex-space-between {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.flex-column-space-between {
    display: flex;
    justify-content: space-between;
    flex-direction: column;
}

.flex-column-space-between-center {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-direction: column;
}

.flex-wrap {
    display: flex;
    flex-wrap: wrap;
}

.navbar-title {
    padding-left: 70rpx;
    color: #ffffff;
    font-size: 34rpx;
}

.b-number-box {
    /deep/.u-icon-minus {
        width: 60rpx !important;
        height: 60rpx !important;
        border-radius: 8rpx !important;
        background: #e1e1e1 !important;
        color: #999999 !important;
    }

    /deep/.u-number-input {
        background: transparent !important;
        color: #111111 !important;
        font-weight: bold;
        width: 80rpx !important;
        font-size: 32rpx !important;
    }

    /deep/.u-icon-plus {
        background: $uni-color-theme !important;
        color: #ffffff !important;
        width: 60rpx !important;
        height: 60rpx !important;
        border-radius: 8rpx !important;
    }
}
</style>
